//
//  LzwEatViewController.m
//  HalfsugarAPP
//
//  Created by 刘志武 on 15/12/30.
//  Copyright © 2015年 刘志武. All rights reserved.
//

#import "LzwEatViewController.h"
#import "Block.h"
#import "LzwEatTableViewCell.h"
#import "LzwEatDetailVC.h"
#import "MJRefresh.h"
#import "AFNetworking.h"
#import "LzwbaseTableView.h"

@interface LzwEatViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) LzwbaseTableView *myEatTableView;


@end

@implementation LzwEatViewController

-(void)dealloc{
    [_arrayEat release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor greenColor];
    
    self.myEatTableView = [[LzwbaseTableView alloc]initWithFrame:[[UIScreen mainScreen]bounds] style:UITableViewStylePlain];
    self.myEatTableView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:self.myEatTableView];
    
    self.myEatTableView.delegate = self;
    self.myEatTableView.dataSource = self;
    
    self.isUpLoading = NO;
    
    // 2.集成上拉下拉功能
    [self addHeader];
    [self addFooter];
    
    [self.myEatTableView registerClass:[LzwEatTableViewCell class] forCellReuseIdentifier:@"cell"];
    
    self.arrayEat = [NSMutableArray array];
    
    
    
    NSString *string = @"http://open3.bantangapp.com/topic/list?app_installtime=1451365479.933367&app_versions=5.1.1&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&device_token=c02c60075e7bab110fbdf27e15de3cb61e97360c4ea3545fd8a5936e46c28ccb&os_versions=9.1&page=0&pagesize=20&scene=15&screensize=640&track_device_info=iPhone5%2C3&track_deviceid=A80585E3-D6AD-4A53-BE1C-5963901C96E5&v=9";
    
    [Block creatingDataTask:string parameters:nil Cookie:nil User_Agent:nil successAFNBlock:^(id resuposeObject) {
       
        NSMutableDictionary *dic = [resuposeObject objectForKey:@"data"];
        
        NSMutableArray *array = [dic objectForKey:@"topic"];
        
        for (NSMutableDictionary *diction in array) {
            
            LzwEatModle *modleEa = [[LzwEatModle alloc]init];
            
            [modleEa setValuesForKeysWithDictionary:diction];
            
            [self.arrayEat addObject:modleEa];
            
            
        }
        
        [self.myEatTableView reloadData];
        
    }];
    
}

#pragma mark --下拉刷新
- (void)addHeader
{
    //    __unsafe_unretained typeof(self) vc = self;
    
    __block LzwEatViewController *vc = self;//因为block块里用self会报警告,所以需要将self声明成block变量
    
    // 添加下拉刷新头部控件
    [self.myEatTableView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        vc.nextPage = 1;//记录页码的
        vc.isUpLoading = NO;//标记为下拉操作
        [vc GetPersonList:vc.nextPage];//重新请求数据
        
    }];
    
#pragma mark 自动刷新(一进入程序就下拉刷新)
    [self.myEatTableView headerBeginRefreshing];
    
}

#pragma mark --上拉加载更多
- (void)addFooter
{
    //    __unsafe_unretained typeof(self) vc = self;
    __block LzwEatViewController *vc = self;
    
    // 添加上拉刷新尾部控件
    [self.myEatTableView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        vc.nextPage ++;
        vc.isUpLoading = YES;//标记为上拉操作
        [vc GetPersonList:vc.nextPage];//请求数据
        
    }];
}

#pragma mark --使用AFN进行数据请求
-(void)GetPersonList:(NSInteger)nextCursor
{
    
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    
    
    NSString *url_string = [NSString stringWithFormat:@"http://open3.bantangapp.com/topic/list?app_installtime=1451365479.933367&app_versions=5.1.1&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&device_token=c02c60075e7bab110fbdf27e15de3cb61e97360c4ea3545fd8a5936e46c28ccb&os_versions=9.1&page=%ld&pagesize=20&scene=15&screensize=640",nextCursor];
    
    
    
    
       AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [netWorkManager stopMonitoring];
        
        NSMutableArray *arrayA = [responseObject objectForKey:@"data"];
        
        
        if (self.isUpLoading == NO) {
            //说明是下拉，就要清空数组中的数据
            [self.arrayEat removeAllObjects];
        }
        
        for (NSMutableDictionary *dict in arrayA) {
            
            LzwEatModle *modle = [[LzwEatModle alloc]init];
            
            [modle setValuesForKeysWithDictionary:dict];
            
            [self.arrayEat addObject:modle];
            
        }
        
        
        
        [self.myEatTableView footerEndRefreshing];
        [self.myEatTableView headerEndRefreshing];
        [self.myEatTableView reloadData];
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"失败==== %@",error);
        
    }];
    
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.arrayEat.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    LzwEatTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.modleEat = [self.arrayEat objectAtIndex:indexPath.row];
    
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    LzwEatDetailVC *eatVC = [[LzwEatDetailVC alloc]init];
    
    eatVC.modleDetailEat = [self.arrayEat objectAtIndex:indexPath.row];
    
    [self.navigationController pushViewController:eatVC animated:YES];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 260;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
